package com.example.mobiledatapackage.exceptionHandler;

import com.example.mobiledatapackage.exception.BusinessException;
import com.example.mobiledatapackage.response.uniformat.ResultData;
import com.example.mobiledatapackage.response.uniformat.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {

    /**
     * 默认全局异常处理
     * @param e the e
     * @return ResultData
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData<String> baseExceptionHandler(Exception e) {
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return ResultData.fail(ReturnCode.SERVE_ERROR.getCode(),e.getMessage());
    }

    /**
     * 处理参数校验异常
     * @param e the e
     * @return ResultData
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    @ResponseBody
    public ResultData<Object> validExceptionHandler(BindException e) {
        String exceptionMsg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        log.warn("参数校验异常: {}", exceptionMsg);
        return ResultData.fail(ReturnCode.ARGS_VALIDATION_ERROR.getCode(), exceptionMsg);
    }

    /**
     * 处理业务异常
     * @param e the e
     * @return ResultCode
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResultData<Object> businessExceptionHandler(BusinessException e) {
        String iMsg = e.getInternalMsg();                   // 内部报错信息
        String eMsg = e.getErrorType().getExternalMsg();    // 外部报错信息
        log.warn("业务异常：{}", iMsg);
        return ResultData.fail(ReturnCode.BUSINESS_ERROR.getCode(), eMsg);
    }

}
